<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
     <!-- <el-form-item label="预制菜名称" prop="premaidFoodName">
        <el-input
          v-model="queryParams.premaidFood.premaidFoodName"
          placeholder="请输入预制菜名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="客户名称" prop="customerName">
        <el-input
          v-model="queryParams.customer.cusromerName"
          placeholder="请输入客户名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <!-- <el-form-item label="订单总价" prop="orderPrice">
        <el-input
          v-model="queryParams.orderPrice"
          placeholder="请输入订单总价"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <el-form-item label="订单状态" prop="orderState">
        <!-- <el-input
          v-model="queryParams.orderState"
          placeholder="请输入订单状态"
          clearable
          @keyup.enter.native="handleQuery"
        /> -->
        <el-select
                  v-model="queryParams.orderState"
                  placeholder="请选择订状态"
                  clearable
                  style="width: 180px"
                >
          <el-option
            v-for="(value, key) in map.boolean"
            :key="key"
            :label="value"
            :value="parseInt(key)"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间">
        <el-date-picker
          v-model="daterangeRderAddtime"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:orders:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:orders:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:orders:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-close"
          size="mini"
          :disabled="single"
          @click="handleDistribution"
          v-hasPermi="['system:orders:distribution']"
        >配货</el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-close"
          size="mini"
          :disabled="multiple"
          @click="handleClose"
          v-hasPermi="['system:orders:close']"
        >关闭订单</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:orders:export']"
        >导出</el-button>
      </el-col> -->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="ordersList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="订单号" align="center" prop="orderId" />
      <!-- <el-table-column label="预制菜id" align="center" prop="orderPremaidFoodId" />
      <el-table-column label="客户id" align="center" prop="orderCustomerId" /> -->
      <el-table-column label="预制菜名称" align="center" prop="premaidFood.premaidFoodName">
        <template slot-scope="scope">
          <span>{{ scope.row.premaidFood.premaidFoodName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="客户名称" align="center" prop="customer.cusromerName">
        <template slot-scope="scope">
          <span>{{ scope.row.customer.cusromerName }}</span>
        </template>
      </el-table-column>

      <el-table-column label="订单数量" align="center" prop="orderCount" />
     <!-- <el-table-column label="订单总价" align="center" prop="orderPrice" /> -->
      <!-- <el-table-column label="订单状态" align="center" prop="orderState" /> -->
      <el-table-column label="订单状态" align="center" prop="orderState">
        <template slot-scope="scope">
          <span>{{ map.boolean[scope.row.orderState] }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="rderAddtime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.rderAddtime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:orders:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:orders:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改订单管理 对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="预制菜" prop="orderPremaidFoodId">
          <!-- <el-input v-model="form.orderPremaidFoodId" placeholder="请输入预制菜id" /> -->
          <el-select
                      v-model="form.orderPremaidFoodId"
                      placeholder="请选择预制菜"
                      filterable
                      clearable
                      style="width: 100%"
                    >
            <el-option
              v-for="food in foodOptions"
              :key="food.premaidFoodId"
              :label="food.premaidFoodName"
              :value="food.premaidFoodId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="客户" prop="orderCustomerId">
          <!-- <el-input v-model="form.orderCustomerId" placeholder="请输入客户id" /> -->
          <el-select
                      v-model="form.orderCustomerId"
                      placeholder="请选择客户"
                      filterable
                      clearable
                      style="width: 100%"
                    >
            <el-option
              v-for="customer in customerOptions"
              :key="customer.customerId"
              :label="customer.cusromerName"
              :value="customer.customerId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="订单数量" prop="orderCount">
          <el-input v-model="form.orderCount" placeholder="请输入订单数量" />
        </el-form-item>
      <!--  <el-form-item label="订单总价" prop="orderPrice">
          <el-input v-model="form.orderPrice" placeholder="请输入订单总价" />
        </el-form-item> -->
        <el-form-item label="订单状态" prop="orderState">
         <!-- <el-input v-model="form.orderState" placeholder="请输入订单状态" /> -->
          <el-select
                      v-model="form.orderState"
                      placeholder="请选择订单状态"
                      style="width: 100%"
                    >
            <el-option
              v-for="(value, key) in map.boolean"
              :key="key"
              :label="value"
              :value="parseInt(key)"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listOrders, getOrders, delOrders, addOrders, updateOrders,close,distribution } from "@/api/system/orders";
import { listFood } from "@/api/system/food";
import { listCustomer } from "@/api/system/customer";
export default {
  name: "Orders",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 订单管理 表格数据
      ordersList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 订单状态时间范围
      daterangeRderAddtime: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        orderPremaidFoodId: null,
        orderCustomerId: null,
        orderPrice: null,
        orderState: null,
        rderAddtime: null,
        customer:{cusromerName:null},
        premaidFood: {premaidFoodName: null}


      },
      //订单状态
      map : {boolean: {0:'未提交',1:'配货成功',2:'出库成功',3:'已完成',4:'手动关闭'}},

      foodOptions: [], // 预制菜下拉选项
      customerOptions: [], // 客户下拉选项
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        orderPremaidFoodId: [
          { required: true, message: "请选择预制菜", trigger: "change" }
        ],
        orderCustomerId: [
          { required: true, message: "请选择客户", trigger: "change" }
        ],
        orderCount: [
          { required: true, message: "请输入订单数量", trigger: "blur" },
          { pattern: /^[1-9]\d*$/, message: "请输入正整数" }
        ],
        orderPrice: [
          { required: true, message: "请输入订单总价", trigger: "blur" },
          { pattern: /^\d+(\.\d{1,2})?$/, message: "请输入正确的价格格式" }
        ],
        orderState: [
          { required: true, message: "请选择订单状态", trigger: "change" }
        ]
      }
    };
  },
  created() {
    this.getList();
    this.loadFoodOptions();
    this.loadCustomerOptions();
  },
  methods: {
    /** 加载预制菜下拉选项 */
    loadFoodOptions() {
      listFood().then(response => {
        this.foodOptions = response.rows;
      });
    },

    /** 加载客户下拉选项 */
    loadCustomerOptions() {
      listCustomer().then(response => {
        this.customerOptions = response.rows;
      });
    },

    /** 查询订单管理 列表 */
    getList() {
      this.loading = true;
      this.queryParams.params = {};
      if (null != this.daterangeRderAddtime && '' != this.daterangeRderAddtime) {
        this.queryParams.params["beginRderAddtime"] = this.daterangeRderAddtime[0];
        this.queryParams.params["endRderAddtime"] = this.daterangeRderAddtime[1];
      }
      listOrders(this.queryParams).then(response => {
        this.ordersList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 配货订单操作 */
    async handleDistribution() {
      const orderId =  this.ids
      try {
        await this.$confirm(`确定要为订单 ${orderId[0]} 执行配货吗？`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        });
        this.loading = true;
        const response = await distribution(orderId[0]);
        if (response.code === 200) {
          this.$modal.msgSuccess(response.msg);
          this.getList(); // 刷新列表
        } else {
          this.$modal.msgError(response.msg);
        }
      } catch (error) {
        if (error !== 'cancel') {
          this.$modal.msgError(error.msg );
        }
      } finally {
        this.loading = false;
      }
    },
    /** 关闭订单操作 */
    handleClose(row) {
      const orderIds = row.orderId || this.ids;
      this.$modal.confirm('是否关闭订单').then(function() {
        return close(orderIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("关闭成功");
      }).catch(() => {});
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        orderId: null,
        orderPremaidFoodId: null,
        orderCustomerId: null,
        orderCount: null,
        orderPrice: null,
        orderState: null,
        rderAddtime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.daterangeRderAddtime = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.orderId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加订单管理 ";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const orderId = row.orderId || this.ids
      getOrders(orderId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改订单管理 ";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.orderId != null) {
            updateOrders(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addOrders(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const orderIds = row.orderId || this.ids;
      this.$modal.confirm('是否确认删除订单管理 编号为"' + orderIds + '"的数据项？').then(function() {
        return delOrders(orderIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/orders/export', {
        ...this.queryParams
      }, `orders_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
